<?php

class Message {

    const SNAME  = 'dlkwyy3';
    const SPWD   = 'IllFGzmbD7Qi';
    const TARGET = 'http://cf.51welink.com/submitdata/Service.asmx/g_Submit';
    const SPRDID = '1012808';
    const SIGNATURE = '【酷我】';

    /**
     * 调用该方法发送短信
     */
    public function send ($tophone , $content)
    {
        $environment = Yaf_Registry::get('config')->application->environment;
        if($environment == "offline") return false;
        $post_data = "sname=" . self::SNAME . "&spwd=" . self::SPWD . "&scorpid=&sprdid=" . self::SPRDID . "&sdst=" . $tophone . "&smsg=" . rawurlencode ( $content.self::SIGNATURE );
        $res       = self::Post ( $post_data , self::TARGET );

        /** 记录请求日志 */
        $log = array (
            'tophone' => $tophone ,
            'type'    => 'invitation_user' ,
            'content' => $content ,
            'results' => $res ,
        );
        LogTool::meaasgedataLog ()->log ( json_encode ( $log ) );
        return $res;
    }

    private static function Post ($data , $target)
    {
        $url_info   = parse_url ( $target );
        $httpheader = "POST " . $url_info[ 'path' ] . " HTTP/1.0\r\n";
        $httpheader .= "Host:" . $url_info[ 'host' ] . "\r\n";
        $httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader .= "Content-Length:" . strlen ( $data ) . "\r\n";
        $httpheader .= "Connection:close\r\n\r\n";
//$httpheader .= "Connection:Keep-Alive\r\n\r\n";
        $httpheader .= $data;

        $fd   = fsockopen ( $url_info[ 'host' ] , 80 );
        fwrite ( $fd , $httpheader );
        $gets = "";
        while ( ! feof ( $fd ) )
        {
            $gets .= fread ( $fd , 128 );
        }
        fclose ( $fd );
        if ( $gets != '' )
        {
            $start = strpos ( $gets , '<?xml' );
            if ( $start > 0 )
            {
                $gets = substr ( $gets , $start );
            }
        }
        return $gets;
    }

}
